package com.gmrz.uas.plugin.sm2;


public class SM4Utils {

	public SM4Utils() {
	}

	/**
	 *加密
	 * @param secretKey	密钥
	 * @param plainText	数据
	 * @return
	 */
	public byte[] encryptData_ECB(byte[] secretKey,byte[] plainText) {
		try {
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_ENCRYPT;
			
			SM4 sm4 = new SM4();
			sm4.sm4_setkey_enc(ctx, secretKey);
			byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText);
			return encrypted;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public byte[] decryptData_ECB(byte[] secretKey,byte[] cipherText) {
		try {
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_DECRYPT;
			
			SM4 sm4 = new SM4();
			sm4.sm4_setkey_dec(ctx, secretKey);
			byte[] decrypted = sm4.sm4_crypt_ecb(ctx, cipherText);
			return decrypted;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
//	public String encryptData_CBC(String plainText) {
//		try {
//			SM4_Context ctx = new SM4_Context();
//			ctx.isPadding = true;
//			ctx.mode = SM4.SM4_ENCRYPT;
//
//			byte[] keyBytes;
//			byte[] ivBytes;
//			if (hexString) {
//				keyBytes = Util.hexStringToBytes(secretKey);
//				ivBytes = Util.hexStringToBytes(iv);
//			} else {
//				keyBytes = secretKey.getBytes();
//				ivBytes = iv.getBytes();
//			}
//
//			SM4 sm4 = new SM4();
//			sm4.sm4_setkey_enc(ctx, keyBytes);
//			byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, plainText.getBytes("GBK"));
//			String cipherText = new BASE64Encoder().encode(encrypted);
//			if (cipherText != null && cipherText.trim().length() > 0) {
//				Pattern p = Pattern.compile("\\s*|\t|\r|\n");
//				Matcher m = p.matcher(cipherText);
//				cipherText = m.replaceAll("");
//			}
//			return cipherText;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		}
//	}
//
//	public String decryptData_CBC(String cipherText) {
//		try {
//			SM4_Context ctx = new SM4_Context();
//			ctx.isPadding = true;
//			ctx.mode = SM4.SM4_DECRYPT;
//
//			byte[] keyBytes;
//			byte[] ivBytes;
//			if (hexString){
//				keyBytes = Util.hexStringToBytes(secretKey);
//				ivBytes = Util.hexStringToBytes(iv);
//			}else{
//				keyBytes = secretKey.getBytes();
//				ivBytes = iv.getBytes();
//			}
//
//			SM4 sm4 = new SM4();
//			sm4.sm4_setkey_dec(ctx, keyBytes);
//			byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, new BASE64Decoder().decodeBuffer(cipherText));
//			return new String(decrypted, "GBK");
//		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		}
//	}


}
